home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news
- From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
- Newsgroups: comp.lang.c++
- Subject: Re: A curly one for gurus: possible to create a value array of derived objects?
- Date: Thu, 15 Feb 1996 14:21:16 +0100
- Organization: Fachbereich Informatik, TH Darmstadt
- Message-ID: <3123334C.446B9B3D@intellektik.informatik.th-darmstadt.de>
- References: <4fuho2$d3s@mblisd.macqbl.com.au>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
-
- Steven James Brown wrote:
- >
- > Ok This is a real curly question:
- >
- > Is it possible to create (and manage) a "value" array of objects from
- > derived classes?
- >
- > E.g:
- >
- > struct A { virtual char* name() { return "A"; } };
- > struct B : public A { int data1; virtual char* name() { return "B"; } };
- > struct C : public A { double data2; virtual char* name() { return "C"; } };
- >
- > To be able to provide access to an array of B's and C's without occuring
- > the overhead of pointer indirection, I am hoping it is somehow possible to
- > have something like:
- >
- > #include <stdio.h>
- > main()
- > {
- > A* a = new A[10];
- > B b;
- > C c;
- >
- > a[0] = b;
- > a[1] = c;
- >
- > printf("%s\n", a[0].name());
- > printf("%s\n", a[1].name());
- > }
- >
- > The output from this (as you may have already guessed) is
- > A
- > A
- >
- > and not
- > B
- > C
- >
- > The problem here is I guess "data slicing" and the use of the default operator=.
- > Is it possible to somehow get over this
- > by faking a union? I can't use unions in practice because my derived classes
- > have (default) constructors.
- >
- > The idea for this came from the "Composite" pattern in the Design Patterns
- > book by Gamma/Helm/Johnson/Vlissides. The "A" class above being the "Composite"
- > object, and the "B" and "C" being the "Component" objects.
- >
-
- IMO the easiest way is to wrap pointers to objects of type A,B,C, ...and maintain
- an array of wrapped objects instead.
-
- Enno
-